package com.sxit.myproscenium.system.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxit.myproscenium.common.exception.ServerException;
import com.sxit.myproscenium.common.response.R;
import com.sxit.myproscenium.system.controller.form.CreateOrderForm;
import com.sxit.myproscenium.system.controller.form.GoodsList;
import com.sxit.myproscenium.system.entity.Order;
import com.sxit.myproscenium.system.service.IGoodsService;
import com.sxit.myproscenium.system.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 前端控制器
 *
 * @author wcn
 * @since 2022-04-10
 */
@RestController
@RequestMapping("/system/order")
public class OrderController {

  @Autowired private IOrderService orderService;
  @Autowired private IGoodsService goodsService;

  @SaCheckLogin
  @PostMapping("/createOrder")
  public R createOrder(@RequestBody @Valid CreateOrderForm createOrderForm) {

    long userId = StpUtil.getLoginIdAsLong();

    // 判断库存
    GoodsList[] goodsList = createOrderForm.getGoodsList();
    boolean flag = false;
    for (GoodsList list : goodsList) {
      // 库存够的话返回true
      Boolean isOk = orderService.isOk(list.getGoodsId(), list.getNum());
      if (!isOk) {
        flag = true;
      }
    }

    Order order = new Order();
    order.setOwnder(userId);
    order.setAllPrice(createOrderForm.getAllPrice());
    order.setGoodsList(JSON.toJSON(createOrderForm.getGoodsList()).toString());
    order.setAddressId(createOrderForm.getAddressId());
    order.setExpressPrice(new BigDecimal(6));
    order.setOrderStatus(2);
    order.setRemark(createOrderForm.getRemark());
    order.setCreateTime(LocalDateTime.now());

    if (flag) {
      throw new ServerException("库存不足，请返回从新选择");
    }

    // 插入
    boolean save = orderService.save(order);

    if (save) {
      return R.ok();
    } else {
      return R.error();
    }
  }

  @GetMapping("/getAllList")
  @SaCheckLogin
  public R getAllList() {
    QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
    orderQueryWrapper.eq("ownder", StpUtil.getLoginIdAsLong());
    List<Order> list = orderService.list(orderQueryWrapper);

    return R.ok().put("data", list);
  }

  @GetMapping("/confirmReceipt")
  @SaCheckLogin
  R ConfirmReceipt(@RequestParam("id") Long id) {
    Order order = new Order();
    order.setOrderId(id);
    order.setOrderStatus(13);
    order.setUpdateTime(LocalDateTime.now());

    boolean update = orderService.updateById(order);

    if (update) {
      return R.ok("确认成功");
    } else {
      return R.error("确认失败");
    }
  }
}
